package aom.ju.ss.view.user.shop.management.freightTemplate

import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.LinearLayoutManager
import aom.ju.ss.R
import aom.ju.ss.databinding.EditShippingTemplateActivityHeadBinding
import aom.ju.ss.databinding.EditShippingTemplateActivityItemBinding
import aom.ju.ss.databinding.EditShippingTemplateBinding
import aom.ju.ss.lpInterface.BindViewInterface
import aom.ju.ss.lpInterface.TitleDialogInterface
import aom.ju.ss.mode.UserInfo
import aom.ju.ss.utils.VG
import aom.ju.ss.utils.http.LP_API
import aom.ju.ss.utils.http.OKHttpUtils
import aom.ju.ss.utils.show
import aom.ju.ss.view.base.BaseActivity
import aom.ju.ss.view.base.PAdapter
import aom.ju.ss.view.dialog.TitleDialog
import com.google.gson.Gson


/**
 * 修改运费模板
 */
class EditShippingTemplate : BaseActivity(), BindViewInterface {
    private lateinit var binding: EditShippingTemplateBinding
    private lateinit var pAdapter: PAdapter
    private var list: MutableList<MutableList<String>> = arrayListOf()
    private var listTitle: MutableList<String> = arrayListOf()
    private lateinit var headBinding: EditShippingTemplateActivityHeadBinding
    private var ckp = 0
    private var isEdit = false

    companion object {
        /**
         * 已选择的省
         */
        var selectedProvince = arrayListOf<String>()
    }

    override fun init() {
        binding = viewBinding as EditShippingTemplateBinding
        headBinding =
            DataBindingUtil.inflate(
                layoutInflater,
                R.layout.edit_shipping_template_activity_head,
                null,
                false
            )
        binding.title.title.text = "修改运费模板"
        binding.title.r_title_two.text = "    保存    "
        pAdapter = PAdapter(list, R.layout.edit_shipping_template_activity_item, this)
        binding.list.small.isEnabled = false
        headBinding.title.more.VG(false)
        pAdapter.headerView = headBinding.rootView
        binding.list.mRecycler.layoutManager = LinearLayoutManager(activity)


        list.add(arrayListOf())
        list.add(arrayListOf())
        list.add(arrayListOf())
        list.add(arrayListOf())

        if (intent.hasExtra("mode")) {
            val mode: PostageTemplate =
                Gson().fromJson(intent.getStringExtra("mode"), PostageTemplate::class.java)
            mode.data?.let {
                for (a in it) {
                    list[a.type - 1].addAll(a.province)
                }
                pAdapter.notifyDataSetChanged()
            }
        }

        listTitle.add("特惠邮费配送区域")
        listTitle.add("常规邮费配送区域")
        listTitle.add("偏远地区特殊邮费区域")
        listTitle.add("不配送区域")
        binding.list.mRecycler.adapter = pAdapter


        binding.title.r_title_two.setOnClickListener {

            val listData = arrayListOf<UpData>()

            val ckp = arrayListOf<String>()
            for (a in list) {
                ckp.addAll(a)
            }

            for ((i, a) in list.withIndex()) {
                if (CkAll(ckp)) {
                    val data = UpData()
                    data.type = (i + 1).toString()
                    data.province = a
                    listData.add(data)
                } else {
                    val ls = NewShippingTemplate.plis.minus(ckp)
                    val ac = Gson().toJson(ls)
                    TitleDialog.showMsg(activity, ac + "未设置类型")
                    return@setOnClickListener
                }

            }
            OKHttpUtils(activity)
                .SetApiUrl(LP_API.save_freight_tmp)
                .SetKey(
                    "client_id",
                    "shop_id",
                    "data",
                    "api_version",
                    "platform"
                )
                .SetValue(
                    "1",
                    UserInfo.userInfo?.shop_id,
                    Gson().toJson(listData),
                    "v2",
                    "android"
                )
                .POST(this)


        }
        binding.title.back.setOnClickListener {
            if (isEdit) {
                TitleDialog()
                    .show(activity, object : TitleDialogInterface {
                        override fun ok(view: View?, IsDetermine: Boolean) {
                            if (IsDetermine) {
                                binding.title.r_title_two.performClick()
                            } else {
                                finish()
                            }
                        }
                    })
                    .setConnect("未保存运费模板,是否保存？")
                    .tvCancel("不保存")
                    .tvDetermine("保存")
            } else {
                finish()
            }
        }
    }

    /**
     * 单个全选 或者 其他几种全选 返回true
     * 无需验证剩下的时候选择
     */
    private fun CkAll(ls: List<String>): Boolean {

        for (a in list) {
            if (a.size == NewShippingTemplate.plis.size || ls.size == NewShippingTemplate.plis.size) {
                return true
            }
        }
        return false

    }

    override fun ok(jsonString: String, httpTY: String) {
        super.ok(jsonString, httpTY)
        "保存成功".show()
        setResult(RESULT_OK)
        finish()
    }

    override fun error(e: String, jsonString: String, httpTY: String) {
        super.error(e, jsonString, httpTY)
        e?.show()
    }

    override fun onBackPressed() {
        binding.title.back.performClick()
    }

    override val lay: Int = R.layout.edit_shipping_template
    override fun bandView(b: ViewDataBinding?, position: Int) {
        val ib = b as EditShippingTemplateActivityItemBinding
        ib.line.view.VG(list[position].size != 0)
        ib.city.VG(list[position].size != 0)

        var city = ""
        for ((i, a) in list[position].withIndex()) {
            city += a
            if (i != list[position].size - 1) {
                city += ","
            }
        }
        ib.city.text = city
        ib.rootView.setOnClickListener {
            ckp = position
            selectedProvince.clear()
            for ((i, ra) in list.withIndex()) {
                if (i != position) {
                    for (ca in ra) {
                        selectedProvince.add(ca)
                    }
                }
            }
            startActivityForResult(
                Intent(activity, NewShippingTemplate::class.java)
                    .putExtra("title", listTitle[position])
                    .putExtra("type", (position + 1).toString()), position
            )
        }
        ib.title.title.text = listTitle[position]
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ckp && resultCode == RESULT_OK) {
            data?.let {
                if (data.hasExtra("list")) {
                    data.getStringArrayListExtra("list")?.let { aa ->
                        list[ckp].clear()
                        list[ckp].addAll(aa)
                        pAdapter.notifyDataSetChanged()
                        isEdit = true
                        setResult(RESULT_OK)
                    }
                }
            }
        }

    }

    class UpData {
        var type: String = ""
        var province: List<String> = arrayListOf()
    }
}